﻿using Microsoft.Xna.Framework.Graphics;
using Microsoft.Xna.Framework.Content;

using HMEngine.HMComponents;

namespace HMEngine.HMObjects {
    public class HMModel : IHMHasMaterial, IHMLoadable, IHMRenderable {
        private readonly string myAsset;
        private Model myModel;

        public string Shader { get; set; }
        public VertexDeclaration VertexDeclaration {
            get { return myModel.Meshes[0].MeshParts[0].VertexDeclaration; }
        }

        public HMModel(string asset) {
            myAsset = asset;
        }

        public void LoadContent(GraphicsDevice myDevice, ContentManager myLoader) {
            myModel = myLoader.Load<Model>(myAsset);
        }

        public void Render(GraphicsDevice myDevice) {
            foreach (ModelMesh mesh in myModel.Meshes) {
                myDevice.Indices = mesh.IndexBuffer;

                // Each mesh is made of parts (grouped by texture, etc.)
                foreach (ModelMeshPart part in mesh.MeshParts) {
                    // Change the device settings for each part to be rendered
                    myDevice.VertexDeclaration = part.VertexDeclaration;
                    myDevice.Vertices[0].SetSource(
                        mesh.VertexBuffer,
                        part.StreamOffset,
                        part.VertexStride
                        );

                    // Make sure we use the texture for the current part also
                    myDevice.Textures[0] = ((BasicEffect)part.Effect).Texture;

                    // Finally draw the actual triangles on the screen
                    myDevice.DrawIndexedPrimitives(
                        PrimitiveType.TriangleList,
                        part.BaseVertex,
                        0,
                        part.NumVertices,
                        part.StartIndex,
                        part.PrimitiveCount
                        );
                }
            }
        }
    }
}